package com.listen.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.listen.common.DateFormatUtil;
import com.listen.common.HttpClientUtil;
import com.listen.common.SpecialCharacterHandler;

@WebServlet(urlPatterns = "/login", asyncSupported = true)
public class BadayuanNew extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private List<String> msgList = null;
	
	public static void main(String[] args) {
		BadayuanNew instance = new BadayuanNew();
		String num = "360726199610052639";
		String code [] = num.split(",");
		System.out.println("开始听课：共"+code.length+"个");
		for(int i=0;i<code.length;i++){
			Map<String,String> parmsMap = new ConcurrentHashMap<String,String>();
			//1施工员(10土建 11装饰装修 12 设备安装 13 市政工程)，
			//2标准员
			//3材料员
			//4机械员
			//5安全员
			//6资料员
			//70土建质量员  71装饰装修质量员 72 装饰装修质量员 73 市政工程质量员
			//8劳务员
			parmsMap.put("zy", "11");
			parmsMap.put("txtUserName", code[i]);
			parmsMap.put("txtPwd", "888888");
			parmsMap.put("numBegin", "1");
			parmsMap.put("numEnd", "30");
			System.out.println("开始听第"+(i+1)+"/"+code.length+"个");
			instance.getHtml(parmsMap);
		}
		System.out.println("全部听听完：共"+code.length+"个");
	}

	// 接收页面请求
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		Map<String,String> parmsMap = new ConcurrentHashMap<String,String>();
		String zy = request.getParameter("ZY");
		String txtUserName = request.getParameter("txtUserName");
		String txtPwd = request.getParameter("txtPwd");
		String numBegin = request.getParameter("numBegin");
		String numEnd= request.getParameter("numEnd");
		parmsMap.put("zy", zy);
		parmsMap.put("txtUserName", txtUserName);
		parmsMap.put("txtPwd", txtPwd);
		parmsMap.put("numBegin", numBegin);
		parmsMap.put("numEnd", numEnd);
		getHtml(parmsMap);
		request.setAttribute("page", 1);
		request.setAttribute("msgList", msgList);
		request.getRequestDispatcher("/result.jsp").forward(request, resp);
	}

	//解析八大员综合登录页面，根据用户选择的专业智能进入对应专业的登录页面
	public void getHtml(Map<String,String> parmsMap) {
		msgList = Collections.synchronizedList(new ArrayList<String>());
		String zy = parmsMap.get("zy");
		try {
			if (zy == null || "".equals(zy.trim())) {
				print("未获取到八大员相关职业信息--->ZY=" + zy);
			} else {
				Document doc = Jsoup.connect("http://urdt.cn/Badayuan/badyuan.html").get();
				Elements links = doc.getElementsByTag("a");
				for (Element link : links) {
					String linkHref = link.attr("href");
					if(zy.startsWith("1")){//1为施工员，有两条通道，需要单独处理
						parmsMap.put("zy1Url", "http://urdt.cn/Badayuan/"+linkHref);
						forwordZy1(parmsMap);
						break;
					}else{
						String lastChar = linkHref.substring(linkHref.length() - 1);
						if("7".equals(lastChar)){
							String se = zy.substring(1);
							zy = zy.substring(0,1);
							parmsMap.put("se", se);
							parmsMap.put("zy", zy);
						}
						if (zy.startsWith(lastChar)) {
							String prefixUrl = linkHref.substring(0,linkHref.lastIndexOf("/"));
							parmsMap.put("loginUrl", linkHref);
							parmsMap.put("prefixUrl", prefixUrl);
							toLoginPage(parmsMap);
							break;
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//zy=1，单独处理
	public void forwordZy1(Map<String,String> parmsMap){
		CloseableHttpResponse response = null;
		String zy1Url = parmsMap.get("zy1Url");
		String zy = parmsMap.get("zy");
		try {
			response = HttpClientUtil.getInstance().sendHttpGetResponse(zy1Url);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				Document document = Jsoup.parse(html);
				Elements links = document.getElementsByTag("a");
				if(zy.length()==2){
					Element link = links.get(0);
					String loginUrl = link.attr("href");
					String prefixUrl = loginUrl.substring(0,loginUrl.lastIndexOf("/"));
					String se = zy.substring(1);
					zy = zy.substring(0,1);
					parmsMap.put("se", se);
					parmsMap.put("zy", zy);
					parmsMap.put("prefixUrl", prefixUrl);
					parmsMap.put("loginUrl", loginUrl);
					toLoginPage(parmsMap);
				}else{
					Element link = links.get(1);
					String loginUrl = link.attr("href");
					String prefixUrl = loginUrl.substring(0,loginUrl.lastIndexOf("/"));
					parmsMap.put("prefixUrl", prefixUrl);
					parmsMap.put("loginUrl", loginUrl);
					toLoginPage(parmsMap);
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
			parmsMap.remove("zy1Url");
		}
	}
	
	/**
	 * 解析登录页，获取登录参数
	 * @param 	loginurl 登录地址
	 * @param	prefixUrl 路径前缀(根路径)
	 */
	private void toLoginPage(Map<String,String> parmsMap){
		CloseableHttpResponse response = null;
		String loginUrl = parmsMap.get("loginUrl");
		try {
			response = HttpClientUtil.getInstance().sendHttpGetResponse(loginUrl);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
			    Document document = Jsoup.parse(html);
			    Element parm1 = document.getElementById("__VIEWSTATEGENERATOR");
			    String _viewstategenerator = parm1.attr("value");
			    Element parm2 = document.getElementById("__EVENTVALIDATION");
			    String _eventvalidation = parm2.attr("value");
			    Element parm3 = document.getElementById("__VIEWSTATE");
			    String _viewstate = parm3.attr("value");
			    parmsMap.put("_viewstategenerator", _viewstategenerator);
			    parmsMap.put("_eventvalidation", _eventvalidation);
			    parmsMap.put("_viewstate", _viewstate);
			    this.login(parmsMap);
			}else{
				print("自动获取登录页面参数失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//智能听课第三步：智能登录
	public void login(Map<String,String> parmsMap){
		String loginUrl = parmsMap.get("loginUrl");
		String txtUserName = parmsMap.get("txtUserName");
		String zy = parmsMap.get("zy");
		String se = parmsMap.get("se");
		Map<String, String> maps = new ConcurrentHashMap<String, String>();
        maps.put("__VIEWSTATE", parmsMap.get("_viewstate")); 
        maps.put("__VIEWSTATEGENERATOR", parmsMap.get("_viewstategenerator"));
        maps.put("__EVENTVALIDATION",parmsMap.get("_eventvalidation")); 
        maps.put("txtUserName",parmsMap.get("txtUserName"));
        maps.put("txtPwd",parmsMap.get("txtPwd"));
        maps.put("ddlType", "2");
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        if(se !=null && !"".equals(se.trim())){
        	maps.put("se", parmsMap.get("se"));
        }
        CloseableHttpResponse response = null;
        try {
        	HttpPost httpPost = new HttpPost(loginUrl);// 创建httpPost
        	httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        	httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        	httpPost.setHeader("DNT", "1");
        	httpPost.setHeader("Upgrade-Insecure-Requests", "1");
        	response = HttpClientUtil.getInstance().sendHttpPost(maps,httpPost);
        	int state = response.getStatusLine().getStatusCode();
        	if(state == 302){
        		System.out.println("登录成功! state="+state);
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		String loginCookie = hearders[0].getValue();
        		String sessionId = loginCookie.substring(0, loginCookie.indexOf(";") + 1);
        		String userIdCookie = hearders[1].getValue();
        		String userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
        		String infoCookies = hearders[2].getValue();
        		String info = infoCookies.substring(0, infoCookies.indexOf(";") + 1);
        		//设置登录信息
        		parmsMap.put("sessionId", sessionId);
        		parmsMap.put("userid", userid);
        		parmsMap.put("info", info);
        		//听课
        		updateStudyVideo(parmsMap);
        	}else{
        		print("登录失败！！！当前账户-"+txtUserName+"-所选职业为:"+zy+",请检查职业是否匹配!");
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//智能听课第五步：更新课件状态为已听
	public void updateStudyVideo(Map<String,String> parmsMap){
		int numBegin = Integer.parseInt(parmsMap.get("numBegin"));
		int numEnd = Integer.parseInt(parmsMap.get("numEnd"));
		String sessionId = parmsMap.get("sessionId");
		String userid = parmsMap.get("userid");
		String zy = parmsMap.get("zy");
		String prefixUrl = parmsMap.get("prefixUrl");
		String txtUserName = parmsMap.get("txtUserName");
		String info = parmsMap.get("info");
		CloseableHttpResponse response = null;
		for (int i = numBegin; i <= numEnd; i++) {
			try {
				//构造cookie中的 st
				String date = DateFormatUtil.getDateStr(new Date());
				String day = date.split(" ")[0];
				String hms = date.split(" ")[1];//时分秒
				String st = day + "%20" + URLEncoder.encode(hms,"utf-8");
				//构造cookie中的 rvCode
				String rvCode = i < 10 ? "0000" + i : "000" + i;
				//构造cookie中的 url
				String url = prefixUrl + "/StudentClass/WatchVideo.aspx?id="+rvCode;
				url = SpecialCharacterHandler.replaceAll(url);
				//组装整个cookie
				String cookie = sessionId + userid + info + " RID=" + rvCode + "; totaltime=2281; url=" + url +";checkUid="+ userid.split("=")[1] +" st="+ st +"; nowtime=2281";
				System.out.println(cookie);
				//构造请求参数
				String rvCodeJson = "{\"RVCode\":\"" + rvCode + "\"}";
				String updateUrl = prefixUrl+"/StudentClass3/WatchVideo3.aspx/UpdateStudyType?dt=" + SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
				//构造请求路径
				if("3".equals(zy)){
					updateUrl = prefixUrl+"/StudentClass6/WatchVideo6.aspx/UpdateStudyType?dt=" + SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
				}
				System.out.println(updateUrl);
				HttpPost httpPost = new HttpPost(updateUrl);// 创建httpPost
				httpPost.setHeader("X-Requested-With","XMLHttpRequest");
				httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
				httpPost.setHeader("Accept","application/json, text/javascript, */*; q=0.01");
				httpPost.setHeader("Cookie", cookie);
				httpPost.setHeader("DNT", "1");
				response = HttpClientUtil.getInstance().sendHttpPost(httpPost, rvCodeJson);
				int state = response.getStatusLine().getStatusCode();
				String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
				String msg = (String) JSONObject.fromObject(entityStr).get("d");
				if(state == 200){
					print("账号-"+txtUserName +" 第"+i +"个视频"+msg);
				}else{
					print("账号-"+txtUserName +" 第"+i +"视频播放失败!"+msg);
					break;
				}
				Thread.sleep(600);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				HttpClientUtil.getInstance().closeResource(response);
			}
		}
		logout(parmsMap);
	}
	
	public void logout(Map<String,String> parmsMap){
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		String prefixUrl = parmsMap.get("prefixUrl");
		String zy = parmsMap.get("zy");
		String sessionId = parmsMap.get("sessionId");
		String userid = parmsMap.get("userid");
		String info = parmsMap.get("info");
		try {
			String path = prefixUrl+"/Public/Logout.aspx?id="+zy;
			httpGet = new HttpGet(path);
			String cookie = sessionId + userid + info +" totaltime=2281; checkUid="+userid+"; nowtime=2281";
			httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			httpGet.setHeader("Cookie", cookie);
			response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200 || state == 302){
				print("退出登录成功!");
			}else{
				print("退出登录失败!");
			}
			Thread.sleep(1000);
		} catch (Exception e) {
			print("退出登录异常--->"+e);
			e.printStackTrace();
		}
	}
	
	public void print(String msg){
		msgList.add(msg);
		System.out.println(msg);
	}
}
